package com.zzyq.pc.common.plugin.shiro.filter;

import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.CodeMsg;
import com.zzyq.pc.common.plugin.shiro.TokenManager;
import com.zzyq.pc.utils.HttpUtils;
import com.zzyq.pc.web.user.model.User;

/**
 * 
 * <p>
 * 
 * @Title: KickoutSessionFilter.java
 * @Description: 用户多处登录过滤器
 * @author: Sywd丶吴迪
 * @date: 2017年9月13日 下午2:25:49
 * @version V1.0
 *          <p>
 */
public class KickoutSessionFilter extends AccessControlFilter {

    /**
     * 用于表示多处登录后的跳转地址
     */
    private String kickoutUrl = "/views/index.jsp?kickout=1";

    private String forceUrl = "/views/index.jsp?forceLogout=1";
    /**
     * 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户(false)
     */
    private boolean kickoutAfter = false;
    /**
     * 同一个帐号最大会话数 默认1
     */
    private int maxSession = 1;
    /**
     * session管理
     */
    private SessionManager sessionManager;
    /**
     * cache管理
     */
    private Cache<Integer, Deque<Serializable>> cache;
    /**
     * cache名称
     */
    private String cacheName = "shiro-kickout-session";

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        Subject subject = getSubject(request, response);
        // 如果没有登录，直接进行之后的流程
        if (!subject.isAuthenticated() && !subject.isRemembered()) {
            return true;
        }
        User user = (User) subject.getPrincipal();
        Session session = subject.getSession();
        // 这里直接判断是否session无效(修改信息或被T)
        if (session.getAttribute(TokenManager.SESSION_FORCE_LOGOUT_KEY) != null) {
            // 会话被踢出了
            saveRequest(request);
            if (HttpUtils.isAjax(request)) {// AJAX请求
                String str = HttpUtils.formatData(new StandardDataFormat(), CodeMsg.CODE_LOGIN_EXPIRE,
                        CodeMsg.MSG_LOGIN_EXPIRE, null);
                HttpUtils.out(response, str);
            } else {
                WebUtils.issueRedirect(request, response, forceUrl);
            }
            return false;
        }
        Serializable sessionId = session.getId();
        // 队列控制用户session
        Deque<Serializable> deque = cache.get(user.getUserId());
        if (deque == null) {
            deque = new LinkedList<Serializable>();
            cache.put(user.getUserId(), deque);
        }
        // 如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
            deque.push(sessionId);
        }
        // 如果队列里的sessionId数超出最大会话数，开始踢人
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            if (kickoutAfter) { // 如果踢出后者
                kickoutSessionId = deque.removeFirst();
            } else { // 否则踢出前者
                kickoutSessionId = deque.removeLast();
            }
            try {
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if (kickoutSession != null) {
                    // 设置会话的kickout属性表示踢出了
                    kickoutSession.setAttribute("kickout", true);
                }
            } catch (Exception e) {
                // 啥也不做
            }
        }
        // 如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute("kickout") != null) {
            // 会话被其他设备挤下线
            saveRequest(request);
            if (HttpUtils.isAjax(request)) {// AJAX请求
                String str = HttpUtils.formatData(new StandardDataFormat(), CodeMsg.CODE_LOGIN_ERROR,
                        CodeMsg.MSG_LOGIN_ERROR, null);
                HttpUtils.out(response, str);
            } else {
                WebUtils.issueRedirect(request, response, kickoutUrl);
                // request.getRequestDispatcher(HttpUtils.LOGIN_URL).forward(request,
                // response);
            }
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        subject.logout();
        return false;
    }

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setForceUrl(String forceUrl) {
        this.forceUrl = forceUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public void setCacheName(String cacheName) {
        this.cacheName = cacheName;
    }

    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache(cacheName);
    }

    public Cache<Integer, Deque<Serializable>> getCache() {
        return cache;
    }

}
